use std::collections::HashMap;

/// The context against which a `when` clause is evaluated.
pub type ActivationContext = HashMap<String, String>;

/// Evaluates a `when` clause string.
///
/// For simplicity, this initial implementation only supports:
/// - `key == 'value'`
/// - `key != 'value'`
///
/// It does not support spaces around the operator.
/// A robust implementation should use a proper parsing library.
pub fn eval_when(when_clause: &str, context: &ActivationContext) -> bool {
    if let Some((key, value)) = when_clause.split_once("==") {
        let expected = value.trim().trim_matches('\'');
        return context.get(key.trim()).map_or(false, |v| v == expected);
    }

    if let Some((key, value)) = when_clause.split_once("!=") {
        let expected = value.trim().trim_matches('\'');
        return context.get(key.trim()).map_or(true, |v| v != expected);
    }

    // If the format is unknown, default to false to be safe.
    false
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_eval_when_eq_true() {
        let mut context = ActivationContext::new();
        context.insert("viewId".to_string(), "detailView".to_string());
        assert!(eval_when("viewId == 'detailView'", &context));
    }

    #[test]
    fn test_eval_when_eq_false() {
        let mut context = ActivationContext::new();
        context.insert("viewId".to_string(), "listView".to_string());
        assert!(!eval_when("viewId == 'detailView'", &context));
    }

    #[test]
    fn test_eval_when_neq_true() {
        let mut context = ActivationContext::new();
        context.insert("viewId".to_string(), "listView".to_string());
        assert!(eval_when("viewId != 'detailView'", &context));
    }

    #[test]
    fn test_eval_when_key_missing() {
        let context = ActivationContext::new();
        assert!(!eval_when("viewId == 'detailView'", &context));
    }
}
